package com.medical.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.medical.dao.CollectMapper;
import com.medical.dao.CourseEvaluateMapper;
import com.medical.dao.CourseOrderMapper;
import com.medical.dao.CourseSeeingMapper;
import com.medical.dao.EnterpriseMapper;
import com.medical.dao.HauptstudiumMapper;
import com.medical.dao.LanguageMapper;
import com.medical.dao.SchoolMapper;
import com.medical.entity.Collect;
import com.medical.entity.Enterprise;
import com.medical.entity.Hauptstudium;
import com.medical.entity.Language;
import com.medical.entity.MyException;
import com.medical.entity.ResultBean;
import com.medical.entity.School;
import com.medical.service.SchoolService;
import com.medical.util.LocationUtils;

@Service
@Transactional
public class SchoolServiceImpl implements SchoolService {
	@Resource
	private SchoolMapper dao;
	
	@Resource
	private CourseSeeingMapper csDao;
	
	@Resource
	private CollectMapper cDao;
	
	@Resource
	private CourseOrderMapper oDao;
	
	@Resource
	private LanguageMapper lDao;
	
	@Resource
	private HauptstudiumMapper hDao;
	
	@Resource
	private CourseEvaluateMapper ceDao;
	
	@Resource
	private EnterpriseMapper eDao;
	
	@Override
	public ResultBean<Integer> addSchool(School school) {
		// TODO Auto-generated method stub
		try {
			int num=eDao.selectCount(new EntityWrapper<Enterprise>().eq("userid", school.getUserid()).and().eq("states", 2));
			if(num==0) {
				return new ResultBean<>(new MyException("未认证企业"));
			}
			school.setRelease(true);
			school.setTime(new Date());
			school.setStates(1);
			int count=dao.insert(school);
			if(count>0) {
				return new ResultBean<>(school.getId());
			}else {
				return new ResultBean<>(new MyException("添加异常"));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(new MyException("系统异常"));
		}
	}

	@Override
	public ResultBean<List<Map<String, Object>>> getList(String address, Integer lanuageId, String hauptstudiumid,int score,double longitude,double latitude,int pageIndex,int size,String keyword) {
		// TODO Auto-generated method stub
		StringBuffer whereSql=new StringBuffer(" where 1=1 and name like '%"+keyword+"%' ");
		if(address!=null&&!address.equals("")) {
			whereSql.append(" and s.address like '%"+address+"%'");
		}
		if(lanuageId!=null&&lanuageId!=0) {
			whereSql.append(" and s.languageid like '%"+lanuageId+"%'");
		}
		if(hauptstudiumid!=null&&!hauptstudiumid.equals("")) {
			whereSql.append(" and s.hauptstudiumid like '%"+hauptstudiumid+"%'");
		}
		whereSql.append(" and s.states=2 and s.release=true");
		String orderStr="";
		if(score==1) {         //默认
			orderStr=" order by s.time";
		}
		try {
			List<Map<String, Object>> list=dao.selectTeacherList(whereSql.toString(), orderStr,(pageIndex-1)*size,size);
			List<Map<String, Object>> list1=new ArrayList<>();
			for(Map<String, Object> map:list) {
				Double longitude1=Double.valueOf(map.get("longitude").toString());
				Double latitude1=Double.valueOf(map.get("latitude").toString());
				Double ju=LocationUtils.getDistance(latitude, longitude, latitude1, longitude1);
				map.put("ju", ju);
				int schoolId=Integer.parseInt(map.get("id").toString());
				List<Double> scoreList=csDao.selectAvgScore(schoolId);
				Double fen=0.0;
				for(Double sc:scoreList) {
					fen=fen+sc;
				}
				fen=(fen/scoreList.size());
				DecimalFormat df = new DecimalFormat("#.00");  
				if(fen>0) {
					 map.put("fen", df.format(fen));
				}else {
					map.put("fen", 0.0);
				}
	            //map.put("fen", df.format(fen));
				list1.add(map);
			}
			if(score==3) {   //距离
				
				 Collections.sort(list1, new Comparator<Map<String, Object>>() {
			            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
			            	Double name1 = Double.valueOf(o1.get("ju").toString()) ;//name1是从你list里面拿出来的一个 
			            	Double name2 = Double.valueOf(o2.get("ju").toString()) ; //name1是从你list里面拿出来的第二个name
			                return name1.compareTo(name2);
			            }
			        });
				
			}else if(score==2) {   //人气
				
				 Collections.sort(list1, new Comparator<Map<String, Object>>() {
			            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
			                Double name1 = Double.valueOf(o1.get("fen").toString()) ;//name1是从你list里面拿出来的一个 
			                Double name2 = Double.valueOf(o2.get("fen").toString()) ; //name1是从你list里面拿出来的第二个name
			                return name1.compareTo(name2);
			            }
			        });
			}
			return new ResultBean<>(list1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<School> getByUserid(int userId) {
		// TODO Auto-generated method stub
		try {
			School sc=dao.selectList(new EntityWrapper<School>().eq("userid", userId)).get(0);
			return new ResultBean<>(sc);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<Map<String, Object>> selectById(int id, int userId) {
		// TODO Auto-generated method stub
		try {
			Map<String, Object> map=new HashMap<>();
			School sc=dao.selectById(id);
			List<Collect> list=cDao.selectList(new EntityWrapper<Collect>().eq("userid", userId).and().eq("collecttype", 9).and().eq("collectid", id));
			if(list.size()>0) {
				map.put("isCollect", true);
			}else {
				map.put("isCollect", false);
			}
			map.put("school", sc);
			int fuNum=oDao.serviceCount(id);
			map.put("fuNum", fuNum);
			String[] languageid=sc.getLanguageid().split(",");
			String[] language=new String[languageid.length];
			int i=0;
			for(String la:languageid) {
				Language lang=lDao.selectById(Integer.parseInt(la));
				language[i]=lang.getLanguage();
				i++;
			}
			String[] hauptstudiumid=sc.getHauptstudiumid().split(",");
			String[] hauptstudium=new String[hauptstudiumid.length];
			i=0;
			for(String la:hauptstudiumid) {
				Hauptstudium lang=hDao.selectById(Integer.parseInt(la));
				hauptstudium[i]=lang.getHauptstudium();
				i++;
			}
			Double fen=ceDao.selectAvgScoreBySchoolId(id);
			map.put("fen", fen);
			map.put("language", language);
			map.put("hauptstudium", hauptstudium);
			return new  ResultBean<Map<String,Object>>(map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<Integer> getListCount(String address, Integer lanuageId, String hauptstudiumid, String keyword) {
		// TODO Auto-generated method stub
		StringBuffer whereSql=new StringBuffer(" where 1=1 and name like '%"+keyword+"%' ");
		if(address!=null&&!address.equals("")) {
			whereSql.append(" and s.address like '%"+address+"%'");
		}
		if(lanuageId!=null&&lanuageId!=0) {
			whereSql.append(" and s.languageid like '%"+lanuageId+"%'");
		}
		if(hauptstudiumid!=null&&!hauptstudiumid.equals("")) {
			whereSql.append(" and s.hauptstudiumid like '%"+hauptstudiumid+"%'");
		}
		whereSql.append(" and s.states=2");
		int count=dao.selectTeacherListCount(whereSql.toString());
		return new ResultBean<Integer>(count);
	}

}
